package com.vitabuybuy.tv.ui

import android.os.Bundle
import android.webkit.URLUtil
import androidx.lifecycle.Observer
import com.library.common.base.BaseActivity
import com.vitabuybuy.tv.R
import com.vitabuybuy.tv.databinding.ActivityWebviewBinding
import com.vitabuybuy.tv.ui.viewmodel.NoViewModel
import com.vitabuybuy.tv.utils.WebViewUtils
import kotlinx.android.synthetic.main.activity_webview.*

/**
 * 作者：SimGa
 * 日期：2019/5/17
 * 时间：17:47
 * 包名：com.seefun.app.ui
 */
class WebViewActivity : BaseActivity<NoViewModel, ActivityWebviewBinding>() {

    override val isUseBaseTitleBar: Boolean
        get() = true
    override val layoutId: Int
        get() = R.layout.activity_webview

    private var titleStr: String? = ""
    private var url: String? = ""
    private var id: Int? = null

    companion object {
        fun openActivity(context: BaseActivity<*, *>, title: String, url: String, id: Int) {
            val bundle = Bundle()
            bundle.putString("title", title)
            bundle.putString("url", url)
            bundle.putInt("id", id)
            context.startActivity(bundle, WebViewActivity::class.java)
        }
    }

    override fun onGetBundle(bundle: Bundle?) {
        titleStr = bundle?.getString("title")
        url = bundle?.getString("url")
        id = bundle?.getInt("id")
    }


    override fun initView(savedInstanceState: Bundle?) {
        mBinding.webView.defaultSetting()
        if (id == -1) {
            if (titleStr!!.length > 14) setTitle(titleStr!!.substring(0, 14) + "...") else setTitle(
                titleStr!!
            )
            if (URLUtil.isValidUrl(url)) {
                mBinding.webView.loadUrl(url)
            } else {
                mBinding.webView.loadDataWithBaseURL(
                    null,
                    WebViewUtils.htmlContent(url),
                    "text/html",
                    "UTF-8",
                    null
                )
            }
        }
    }

    override fun observeData() {
        if (id != -1) {
            viewModel.loadWebViewContet(id)
        }
        viewModel.webContent.observe(this, Observer {
            if (it.title!!.length > 14) setTitle(it.title!!.substring(0, 14) + "...") else setTitle(
                it.title!!
            )
            if (URLUtil.isValidUrl(url)) {
                mBinding.webView.loadUrl(it.content)
            } else {
                mBinding.webView.loadDataWithBaseURL(
                    null,
                    WebViewUtils.htmlContent(it.content),
                    "text/html",
                    "UTF-8",
                    null
                )
            }
        })
    }
}
